package com.wf.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.impl.AbstractEngineConfiguration;
import org.flowable.common.engine.impl.EngineConfigurator;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
import javax.sql.DataSource;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author mpk
 * @since 2024/8/26 13:38:53
 */

@Configuration
@Slf4j
public class FlowableConfig  implements EngineConfigurator {


    private  static  AtomicBoolean initialized= new AtomicBoolean();
    @Override
    public void beforeInit(AbstractEngineConfiguration abstractEngineConfiguration) {

        if(initialized.compareAndSet(false,true))
        {
            DataSource dataSource = abstractEngineConfiguration.getDataSource();

            if(dataSource instanceof TransactionAwareDataSourceProxy)
            {
                 dataSource = ((TransactionAwareDataSourceProxy) dataSource).getTargetDataSource();
            }
            if(dataSource instanceof DynamicRoutingDataSource)
            {
                dataSource = ((DynamicRoutingDataSource) dataSource).getDataSource("flowable");
                abstractEngineConfiguration.setDataSource(dataSource);
            }
            log.info("flowable数据源切换成功");
        }
    }

    @Override
    public void configure(AbstractEngineConfiguration abstractEngineConfiguration) {

    }

    @Override
    public int getPriority() {
        return 0;
    }
}
